package com.kaoshi.myweb.common.utils;




import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.List;

/**
 * 使用jdom解析xml，支持XPath
 * 测试类 com.kaoshi.myweb.common.test.XMLUtilTest
 */
public class XMLUtil
{
	private Document doc;

	private XMLUtil(InputStream is) throws JDOMException, IOException
	{
		this.doc = null;
		SAXBuilder builder = new SAXBuilder();

		Charset charset = null;
		if (Charset.isSupported("GBK"))
		{
			charset = Charset.forName("GBK");
		}

		Reader r;
		if (charset == null)
			r = new InputStreamReader(is);
		else
			r = new InputStreamReader(is, charset);
		
		this.doc = builder.build(r);
	}
	
	public static XMLUtil getInsance(InputStream is) throws JDOMException, IOException
	{
		return new XMLUtil(is);
	}
	
	public List<Element> getByXpath(String xpath) throws JDOMException
	{

		List<Element> elements = XPath.selectNodes(this.doc, xpath);
		return elements;
	}
}